const gulp = require('gulp'),
      htmlmin = require('gulp-htmlmin')
      del = require('del')
      cleanCss = require('gulp-clean-css')
      autoprefixer = require('gulp-autoprefixer')
      uglify = require('gulp-uglify')
      babel = require('gulp-babel')
      sass = require('gulp-sass')
      connect = require('gulp-connect')
//路径集中化管理
const path = {
    html:{
        src:'src/**/*.html',
        dest:'dist'
    },
    css:{
        src:'src/css/**/*.scss',
        dest:'dist/css'
    },
    js:{
        src:'src/js/**/*,js',
        dest:'dist/js'
    },
    img:{
        src:'src/imgs/**/*',
        dest:'dist/imgs'
    },
    libs:{
        src:'src/libs/**/*',
        dest:'dist/libs'
    }
    

}

//制定一个html任务：压缩html代码
const html = () =>{
   return gulp.src(path.html.src)
        .pipe(htmlmin({
            removeComments: true,//清除HTML注释
        	collapseWhitespace: true,//压缩HTML
        	collapseBooleanAttributes: true,//省略布尔属性的值 <input checked="true"/> ==> <input checked />
      		removeEmptyAttributes: true,//删除所有空格作属性值 <input id="" /> ==> <input />
      		removeScriptTypeAttributes: false,//删除<script>的type="text/javascript"
      		removeStyleLinkTypeAttributes: true,//删除<style>和<link>的type="text/css"
      		minifyJS: true,//压缩页面JS
      		minifyCSS: true//压缩页面CSS 
        }))
        .pipe(gulp.dest(path.html.dest))
        .pipe(connect.reload())
}

//制定css任务
const css = () =>{
    return gulp.src(path.css.src)
               .pipe(sass())
               .pipe(autoprefixer({
                   presets:['@babel/env']
               }))
               .pipe(cleanCss())
               .pipe(gulp.dest(path.css.dest))
               .pipe(connect.reload())
}

//制定js任务
const js = () =>{
    return gulp.src(path.js.src)
    .pipe(babel({
        presets:['@babel/env']
    }))
    .pipe(uglify())
    .pipe(gulp.dest(path.js.dest))
    .pipe(connect.reload())
}

//开启服务器
const server = ()=>{
    connect.server({
        root:'dist',//项目根路径dist
        livereload:true, //支持热更新
        port:2020 //配置端口号
    })
}

//删除dist
const deldist = () =>del('dist')


//复制图片和libs里面文件
const img = () => gulp.src(path.img.src).pipe(gulp.dest(path.img.dest))
const libs = () => gulp.src(path.libs.src).pipe(gulp.dest(path.libs.dest))

//监听
const watch = () =>{
    gulp.watch(path.html.src, html)
    gulp.watch(path.css.src, css)
    gulp.watch(path.js.src, js)

}


//导出任务把gulpfile.js文件作为一个自定义模块将任务导出
module.exports.default = gulp.series(deldist, gulp.parallel(html, css, js, img, libs, server, watch))
